from django.shortcuts import render
import logging
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from rest_framework_jwt.settings import api_settings


from QQLoginTool.QQtool import OAuthQQ
from carts.utils import merge_cart_cookie_to_redis


from .models import OAuthQQUser
from .utils import generate_save_user_token
from .models import User
from .serializers import QQAuthUserSerializer


# Create your views here.


logger = logging.getLogger("django")

# url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
# 获取扫描二维码的页面
class QQAuthURLView(APIView):
    def get(self, request):
        # 获取前段发送过来的请求参数,用来保存登录后跳转的路径,在qqtool中的OAuthQQ使用
        params = request.query_params.get("next")
        if not params:
            params = "/"

        # 创建OAUTHQQ对象
        qauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=params)

        # 调用方法获取url
        login_url = qauthqq.get_qq_url()
        # 返回
        return Response({"login_url": login_url})


# /oauth/qq/user/
# 获取access_token值
class QQAuthUserView(GenericAPIView):

    def get(self, request):

        try:
            #　获取ｃｏｄｅ
            qq_code = request.query_params["code"]
            # params = request.query_params["state"]

        except Exception as e:
            logger.info(e)
            return Response({"message": "code不可用"}, status=status.HTTP_400_BAD_REQUEST)

        # 创建OAUTHQQ对象
        qauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI)
                          # state=params)

        try:
            # 获取access_token
            access_token =  qauthqq.get_access_token(qq_code)
            # 获取ｏｐｅｎ＿ｉｄ
            open_id = qauthqq.get_open_id(access_token)
        except Exception as e:
            logger.info(e)
            return Response({"message": "服务不可用"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            oauthqquser_model = OAuthQQUser.objects.get(openid=open_id)
        # 如果此openid没有绑定过美多商城用户返回一个openid
        # return Response({'access_token': openid})
        # 如果此openid没有绑定过用户,那么把openid返回给前端
        except OAuthQQUser.DoesNotExist:
            openid_access_token = generate_save_user_token(open_id)
            return Response({"access_token": openid_access_token})
        else:
            # 如果关联过ｑｑ的直接手动生成ｔｏｋｅｎ
            user = oauthqquser_model.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)


            # 做为合并购物车做准备
            resp = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 调用合并购物车的方法
            resp = merge_cart_cookie_to_redis(request, resp, user)

            return resp


    def post(self, request):
        serializer = QQAuthUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 响应
        resp = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })

        resp = merge_cart_cookie_to_redis(request, resp, user)

        return resp





